package com.xcalendar.servlets;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.xcalendar.constant.XConstants;
import com.xcalendar.database.dao.EventDAO;
import com.xcalendar.database.dao.LocationDAO;
import com.xcalendar.database.table.Event;
import com.xcalendar.database.table.User;
import com.xcalendar.exception.IncorrectNameOrPasswordException;
import com.xcalendar.management.EventManager;
import com.xcalendar.management.UserManager;
import com.xcalendar.managementImpl.EventManagerImpl;
import com.xcalendar.managementImpl.UserManagerImpl;

@SuppressWarnings("serial")
public class EditEventController extends HttpServlet {
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute(XConstants.SESSION_USER);
		EventManager eventManager = new EventManagerImpl();
		StringBuilder error = new StringBuilder();
		EventDAO eventDao = new EventDAO();
		String id = request.getParameter("id");
		String title = request.getParameter("title");
		String description = request.getParameter("description");
		String start = request.getParameter("start");
		start = start.replaceAll("[?]", " ");
		String end = request.getParameter("end");
		end = end.replaceAll("[?]", " ");
		String defaultView = request.getParameter("view");
		String locationKey = request.getParameter("locationKey");
		
		System.out.println(locationKey);
		
		Date sDate = new Date(start);
		Date eDate = new Date(end);
		System.out.println(sDate.toString());
		Event event = new Event();
		event.setKey(KeyFactory.stringToKey(id));
		event.setTitle(title);
		event.setDescription(description);
		event.setStartTime(sDate);
		event.setEndTime(eDate);
		if (!locationKey.equals("Select your locations")) event.setLocationKey(KeyFactory.stringToKey(locationKey));
		System.out.println("editCon"+event.getLocationKey());
		eventManager.updateEvent(event);
		
		UserManager um = new UserManagerImpl();
		try {
			user = um.login(user.getUserName(), user.getPassword());
		} catch (IncorrectNameOrPasswordException e) {
			error.append("Incorrect username Or wrong password !");
		    request.setAttribute(XConstants.WRONY_MESSAGE, error.toString());
		    RequestDispatcher view = request.getRequestDispatcher("welcome.jsp");
		    view.forward(request, response);
		}
		JSONArray jArray = new JSONArray();
		List<Event> events = user.getEvents();
		for (Event event1 : events) {
			Key k = event1.getKey();
			event = eventDao.readEvent(k);
			JSONObject obj = new JSONObject();
			
			try {
				SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				obj.put("id", KeyFactory.keyToString(event.getKey()));
				obj.put("title", event.getTitle());
				if (event.getLocationKey()!=null) {
					obj.put("locationKey", KeyFactory.keyToString(event.getLocationKey()));
					LocationDAO l = new LocationDAO();					
					obj.put("locationName", l.readLocation(event.getLocationKey()).getLocationName());
					//System.out.println(l.readLocation(event.getLocationKey()).getLocationName());
				}
				obj.put("description", event.getDescription());
				obj.put("start", time.format(event.getStartTime()));
				obj.put("end", time.format(event.getEndTime()));
				obj.put("allDay", false);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			jArray.put(obj);	
		}
		jArray.put(events.size());

		
		if (user != null) {
			session.setAttribute(XConstants.SESSION_USER, user);
			session.setAttribute(XConstants.ISLOGGED, "true");
			session.setAttribute(XConstants.JSONEVENTS, jArray.toString());
			session.setAttribute(XConstants.DEFAULTVIEW, defaultView);
			RequestDispatcher view = request.getRequestDispatcher("homepage_calendar.jsp");
		    view.forward(request, response);
		}
	}
}
